package com.hdl.conf;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.*;
import java.util.stream.Collectors;

public class RedisClusterConf {
    /** 主机和端口list，字符串分隔 */
    private static List<String> hostAndPortListStr;
    /** 主机和端口liss */
    private static Set<HostAndPort> hostAndPorts;
    /** JedisCluster对象，保持单例 */
    private static JedisCluster jedisCluster;

    /**
     * 初始化
     */
    public static void init(String... urls){
        RedisClusterConf.hostAndPortListStr = Arrays.asList(urls);
    }
    /**
     * 初始化
     */
    public static void init(List<String> urls){
        RedisClusterConf.hostAndPortListStr = urls;
    }

    /** 获取单列的RedisCluster */
    public static JedisCluster getJedisClusterInstance(){
        if (jedisCluster == null){
            synchronized (RedisClusterConf.class){
                if (jedisCluster == null){
                    if (hostAndPortListStr == null || hostAndPortListStr.size() == 0){
                        throw new RuntimeException("redis 集群参数未配置");
                    }

                    // 获取并指文件并给HostAndPort集合赋值
                    hostAndPorts = hostAndPortListStr.stream().map(
                            s->{
                                String[] split = s.split(":");
                                return new HostAndPort(split[0], Integer.parseInt(split[1]));
                            }
                    ).collect(Collectors.toSet());
                    // 真正创建jedisCluster对象
                    jedisCluster = jedisCluster();
                }
            }
        }
        return jedisCluster;
    }


    private static JedisCluster jedisCluster(){
        return new JedisCluster(hostAndPorts, jedisPoolConfig());
    }

    private static JedisPoolConfig jedisPoolConfig(){
        return new JedisPoolConfig();
    }
}
